package cn.ug.activity.web.controller;

import cn.ug.activity.bean.ChannelActivationBean;
import cn.ug.activity.bean.ChannelBean;
import cn.ug.activity.bean.ChannelStatisticsBean;
import cn.ug.activity.bean.FundsRecordBean;
import cn.ug.activity.mapper.entity.ChannelView;
import cn.ug.activity.mapper.entity.CouponChannel;
import cn.ug.activity.service.ChannelActivationService;
import cn.ug.activity.service.ChannelService;
import cn.ug.activity.web.utils.ExcelUtil;
import cn.ug.aop.RequiresPermissions;
import cn.ug.bean.base.DataTable;
import cn.ug.bean.base.Page;
import cn.ug.bean.base.SerializeObject;
import cn.ug.bean.type.ResultType;
import cn.ug.config.AplicationResourceProperties;
import cn.ug.core.SerializeObjectError;
import cn.ug.util.PaginationUtil;
import cn.ug.util.UF;
import cn.ug.web.controller.BaseController;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

import static cn.ug.util.ConstantUtil.NORMAL_TIME_FORMAT;

@RestController
@RequestMapping("channel")
public class ChannelController extends BaseController {
    @Autowired
    private ChannelService channelService;
    @Autowired
    protected AplicationResourceProperties properties;
    @Autowired
    private ChannelActivationService channelActivationService;

    @RequestMapping("/activation/transform")
    public SerializeObject transform(String uuid) {
        if (channelActivationService.updateStatus(uuid)) {
            return new SerializeObject(ResultType.NORMAL, "00000001");
        } else {
            return new SerializeObject(ResultType.ERROR, "00000005");
        }
    }

    @RequestMapping("/activation")
    public SerializeObject<ChannelActivationBean> getActivation(String uuid) {
        return new SerializeObject<>(ResultType.NORMAL, channelActivationService.findByUuid(uuid));
    }

    @RequestMapping("/ios/activation")
    public String iOSActivation(String adid, String cid, String idfa, String mac, String os, String timestamp, String callback_url, String callback) {
        getLog().info("今日头条IOS渠道激活：adid = " + adid + ", cid = " + cid + ", idfa = " + idfa + ", mac = " + mac + ", os = " + os + ", timestamp = " + timestamp + ", callback_url =" + callback_url+
            ", callback = " + callback);

        ChannelActivationBean bean = new ChannelActivationBean();
        bean.setAdid(adid);
        bean.setCid(cid);
        bean.setUuid(idfa);
        bean.setMac(mac);
        bean.setOs(os);
        if (StringUtils.isNotBlank(timestamp)) {
            SimpleDateFormat dateFormat = new SimpleDateFormat(NORMAL_TIME_FORMAT);
            Date time = new Date(Long.parseLong(timestamp));
            bean.setTimestamp(dateFormat.format(time));
        }
        bean.setCallbackUrl(callback_url);
        bean.setCallback(callback);
        channelActivationService.save(bean);
        return "success";
    }

    @RequestMapping("/android/activation")
    public String androidActivation(String adid, String cid, String imei, String mac, String os, String timestamp, String callback_url, String callback) {
        getLog().info("今日头条安卓渠道激活：adid = " + adid + ", cid = " + cid + ", imei = " + imei + ", mac = " + mac + ", os = " + os + ", timestamp = " + timestamp + ", callback_url =" + callback_url+
                ", callback = " + callback);
        ChannelActivationBean bean = new ChannelActivationBean();
        bean.setAdid(adid);
        bean.setCid(cid);
        bean.setUuid(imei);
        bean.setMac(mac);
        bean.setOs(os);
        if (StringUtils.isNotBlank(timestamp)) {
            SimpleDateFormat dateFormat = new SimpleDateFormat(NORMAL_TIME_FORMAT);
            Date time = new Date(Long.parseLong(timestamp));
            bean.setTimestamp(dateFormat.format(time));
        }
        bean.setCallbackUrl(callback_url);
        bean.setCallback(callback);
        boolean result = channelActivationService.save(bean);
        getLog().info("result= " + result);
        return "success";
    }

    @GetMapping(value = "/{id}")
    public SerializeObject get(@PathVariable String id) {
        if(StringUtils.isBlank(id)) {
            return new SerializeObjectError("00000002");
        }
        ChannelBean entity = channelService.get(id);
        if(null == entity || StringUtils.isBlank(entity.getId())) {
            return new SerializeObjectError("00000003");
        }
        return new SerializeObject<>(ResultType.NORMAL, entity);
    }

    @RequiresPermissions("activity:channel:save")
    @PostMapping
    public SerializeObject save(@RequestHeader String accessToken, ChannelBean entity) {
        if(null == entity || StringUtils.isBlank(entity.getName())) {
            return new SerializeObjectError("22000001");
        }
        if (channelService.save(entity)) {
            return new SerializeObject(ResultType.NORMAL, "00000001");
        } else {
            return new SerializeObject(ResultType.ERROR, "00000005");
        }
    }

    @PostMapping("/notification")
    public SerializeObject notify(String orderNO, String mobile, BigDecimal amount, String sign) {
        if(StringUtils.isBlank(orderNO) || StringUtils.isBlank(mobile) || amount == null
                || amount.doubleValue() <= 0 || StringUtils.isBlank(sign)) {
            return new SerializeObject(504, "00000002");
        }
        String signStr = DigestUtils.md5Hex(amount+mobile+orderNO+properties.getCarChannelKey());
        if (!StringUtils.equals(signStr, sign)) {
            return new SerializeObject(503, "22000116");
        }
        String couponId = "";
        if (amount.doubleValue() == 29999) {
            couponId = properties.getCouponIds().get(0);
        }
        if (amount.doubleValue() == 9999) {
            couponId = properties.getCouponIds().get(1);
        }
        if (amount.doubleValue() == 5750) {
            couponId = properties.getCouponIds().get(2);
        }
        if (amount.doubleValue() == 2980) {
            couponId = properties.getCouponIds().get(3);
        }
        if (amount.doubleValue() == 1410) {
            couponId = properties.getCouponIds().get(4);
        }
        if (amount.doubleValue() == 855) {
            couponId = properties.getCouponIds().get(5);
        }
        if (StringUtils.isBlank(couponId)) {
            return new SerializeObject(505, "22000118");
        }
        CouponChannel couponChannel = channelService.getCouponChannel(orderNO);
        if (couponChannel != null) {
            return new SerializeObject(503, "22000117");
        }
        couponChannel = new CouponChannel();
        couponChannel.setAmount(amount);
        couponChannel.setCouponId(couponId);
        couponChannel.setChannelId(properties.getCarChannelId());
        couponChannel.setMobile(mobile);
        couponChannel.setOrderNO(orderNO);
        if (channelService.save(couponChannel)) {
            return new SerializeObject(ResultType.NORMAL, "00000001");
        } else {
            return new SerializeObject(ResultType.ERROR, "00000005");
        }
    }

    @PostMapping("/view")
    public SerializeObject save(HttpServletRequest request, String channelId) {
        if (StringUtils.isBlank(channelId)) {
            return new SerializeObjectError("00000002");
        }
        String ip = getIpAdrress(request);
        ChannelView channelView = new ChannelView();
        channelView.setChannelId(channelId);
        channelView.setIp(ip);
        if (channelService.saveChannelView(channelView)) {
            return new SerializeObject(ResultType.NORMAL, "00000001");
        } else {
            return new SerializeObject(ResultType.ERROR, "00000005");
        }
    }

    @RequiresPermissions("activity:channel:delete")
    @PutMapping
    public SerializeObject delete(@RequestHeader String accessToken, String[] id) {
        if(null == id || id.length <= 0) {
            return new SerializeObjectError("00000002");
        }
        if (channelService.removeInBatch(id)) {
            return new SerializeObject(ResultType.NORMAL, "00000001");
        } else {
            return new SerializeObject(ResultType.ERROR, "00000005");
        }
    }

    @GetMapping(value = "/export")
    public SerializeObject exportAreaList(@RequestHeader String accessToken, String name) {
        name = UF.toString(name);
        List<ChannelBean> beans = channelService.listRecords(name, 0, 0);
        List<Serializable> list = new LinkedList<Serializable>();
        for(ChannelBean bean: beans) {
            list.add(bean);
        }
        String path = ExcelUtil.writeToExcel(list, -1, properties.getTemplateUrl(), properties.getAccessKey(), properties.getSecretKey(), properties.getBucket(), properties.getFileDomain());
        if (StringUtils.isNotBlank(path)) {
            return new SerializeObject<>(ResultType.NORMAL, "", path);
        } else {
            return new SerializeObjectError("00000005");
        }
    }

    @RequiresPermissions("activity:channel")
    @GetMapping(value = "/list")
    public SerializeObject<DataTable<ChannelBean>> list(@RequestHeader String accessToken, Page page, String name) {
        name = UF.toString(name);
        int total = channelService.countRecords(name);
        page.setTotal(total);
        if (total > 0) {
            int offset = PaginationUtil.getOffset(page.getPageNum(), page.getPageSize());
            int size = PaginationUtil.getPageSize(page.getPageSize());
            if (page.getPageNum() == 0) {
                offset = 0;
                size = 0;
            }
            List<ChannelBean> list = channelService.listRecords(name, offset, size);
            return new SerializeObject<>(ResultType.NORMAL, new DataTable<ChannelBean>(page.getPageNum(), page.getPageSize(), page.getTotal(), list));
        }
        return new SerializeObject<>(ResultType.NORMAL, new DataTable<ChannelBean>(page.getPageNum(), page.getPageSize(), page.getTotal(), new ArrayList<ChannelBean>()));
    }

    @RequiresPermissions("activity:channel:statistics")
    @GetMapping(value = "/statistics")
    public SerializeObject<DataTable<ChannelStatisticsBean>> statistics(@RequestHeader String accessToken, Page page, String startDate, String endDate) {
        startDate = UF.toString(startDate);
        endDate = UF.toString(endDate);
        if (StringUtils.isBlank(startDate) || StringUtils.isBlank(endDate)) {
            startDate = "2018-01-01";
            endDate = UF.getFormatDate(UF.getDateTime());
        }
        int total = channelService.countRecords("");
        page.setTotal(total);
        if (total > 0) {
            List<ChannelStatisticsBean> list = channelService.listRecords(startDate, endDate, PaginationUtil.getOffset(page.getPageNum(), page.getPageSize()), PaginationUtil.getPageSize(page.getPageSize()));
            return new SerializeObject<>(ResultType.NORMAL, new DataTable<ChannelStatisticsBean>(page.getPageNum(), page.getPageSize(), page.getTotal(), list));
        }
        return new SerializeObject<>(ResultType.NORMAL, new DataTable<ChannelStatisticsBean>(page.getPageNum(), page.getPageSize(), page.getTotal(), new ArrayList<ChannelStatisticsBean>()));
    }

    @RequiresPermissions("activity:channel:tradeRecords")
    @GetMapping(value = "/trade/records")
    public SerializeObject<DataTable<FundsRecordBean>> tradeRecords(@RequestHeader String accessToken, Integer type, Page page, String startDate, String endDate) {
        startDate = UF.toString(startDate);
        endDate = UF.toString(endDate);
        type = type == null ? 1 : type;
        int total = channelService.countFundsRecords(type, startDate, endDate);
        page.setTotal(total);
        if (total > 0) {
            List<FundsRecordBean> list = channelService.listFundsRecords(type, startDate, endDate, PaginationUtil.getOffset(page.getPageNum(), page.getPageSize()), PaginationUtil.getPageSize(page.getPageSize()));
            return new SerializeObject<>(ResultType.NORMAL, new DataTable<FundsRecordBean>(page.getPageNum(), page.getPageSize(), page.getTotal(), list));
        }
        return new SerializeObject<>(ResultType.NORMAL, new DataTable<FundsRecordBean>(page.getPageNum(), page.getPageSize(), page.getTotal(), new ArrayList<FundsRecordBean>()));
    }
}
